import React from "react";
import View from "../base/View";
import defaultData from "./data";
import {FileUpload} from "../../../../common/fileupload";
import {WeaLocaleProvider} from "ecCom";
import {IMG_PATH} from "../../../../../constants/form";
import classNames from "classnames";

const getLabel = WeaLocaleProvider.getLabel;
const RADIX = 1024;

export default class AttachmentView extends View {
    getSize(size, hasSpace) {
        const units = ['KB', 'MB'];
        let unit = units[0];
        let i = 0;

        do {
            size = Math.ceil(size / 1024 * 10) / 10;
            unit = units[i++];
        } while(size >= 1024)

        return `${size}${hasSpace ? ' ' : ''}${unit}`;
    }

    renderContent(data, value, isMobile) {
    const { maxSize, maxNum, fileType, customType } = data;
    const tip = isMobile ? getLabel('502473','点击选择上传文件'): '';

    return (
      <FileUpload 
        files={value}
        tip={tip}
        maxNum={maxNum}
        maxSize={maxSize * RADIX * RADIX}
        fileType={fileType}
        customType={customType}
        onChange={this.handleValueChange}
        onUploading={this.toggleFooterDisable}
      />
    );
  }

  renderForReadonly(data, value) {
    const files = value;
    return (
        files.map(({ data, error, link }) => (
            <div className={'wea-edc-upload-inner'} >
              <div className='clearfix wea-edc-upload-item' onClick={() => {window.open(link, '_blank')}}>
                <div className='wea-edc-upload-file-img'><img src={`${IMG_PATH}/attachment-file.png`} /></div>
                <div className={classNames('wea-edc-upload-title', { 'has-error': !!error })}>
                  {!data ? null : `${data.name} ${error ? '' : `(${!isNaN(data.size) ? this.getSize(data.size, true) : data.size})`}`}
                </div>
              </div>
            </div>
        ))
    );
  }
}

AttachmentView.defaultProps = {
  data: defaultData,
  value: ''
};